// import Vue from 'vue'
import nedb from '@/db/nedb'

// initial state
const state = {
  circleMsg: [], // 评论通知
  circleItem: {}, // 某评论的朋友圈信息
  allFriends: []
}

// getters
const getters = {
  // 获取评论通知
  getCircleMsg: (state) => {
    return state.circleMsg
  },
  // 获取某通知对应的朋友圈
  getCircleItem: (state) => {
    return state.circleItem
  },
  // 好友id-好友info map
  getAllFriendsMap: (state) => {
    const fm = {}
    for (const friend of state.allFriends) {
      fm[friend.FriendId] = friend
    }
    return fm
  }
}

// actions
const actions = {
  // 设置所有的好友列表
  SetAllFriends: ({ commit }, wechatId) => {
    nedb.friends.find({ WeChatId: wechatId }, (err, docs) => {
      if (err) return
      commit('SET_ALL_FRIENDS', docs)
    })
  }
}

// mutations
const mutations = {
  // 设置所有的好友列表
  SET_ALL_FRIENDS: (state, docs) => {
    state.allFriends = docs
  },
  // 设置朋友圈数据
  SET_CIRCLE_ITEM: (state, circle) => {
    state.circleItem = circle
  },
  // 更新朋友圈数据
  UPDATE_CIRCLE_ITEM: (state, circleInfo) => {
    if (circleInfo.CircleId === state.circleItem.CircleId && circleInfo.PublishTime) {
      state.circleItem = circleInfo
    }
  },
  // 更新朋友圈消息列表
  UPDATE_CIRCLE_MSG: (state, msgData) => {
    const ms = state.circleMsg.concat(msgData)
    ms.sort((a, b) => {
      return b.PublishTime - a.PublishTime
    })
    state.circleMsg = ms
  },
  // 重置朋友圈消息
  RESET_CIRCLE_MSG: (state) => {
    state.circleMsg = []
  },
  // 移除指定msg
  REMOVE_CIRCLE_MSG: (state, msgIndex) => {
    state.circleMsg.splice(msgIndex, 1)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
